/*
 * =============================================================================
 * "THE BEER-WARE LICENSE" (Revision 42):
 * <eirikb@google.com> wrote this file. As long as you retain this notice you
 * can do whatever you want with this stuff. If we meet some day, and you think
 * this stuff is worth it, you can buy me a beer in return Eirik Brandtzæg
 * =============================================================================
 */
package no.eirikb.roboco.terminal.element;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.eirikb.roboco.terminal.Terminal;

/**
 *
 * @author eirikb
 * @author <a href="mailto:eirikb@google.com">eirikb@google.com</a>
 */
public class WordListElement extends Element {

    private List<String> words;
    private final String WORDFILE = "words";

    public WordListElement(Terminal terminal, int x, int y, StringTokenizer st) {
        super(terminal, x, y, st);// getWidth = wordLength, getHeight = wordAmouns
        readWords(getWidth());
        removeWords(getHeight());
    }

    private void readWords(int wordLength) {
        words = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(getTerminal().getFile().getParent() + File.separator + WORDFILE)));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.length() == wordLength) {
                    words.add(line);
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(WordListElement.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Logger.getLogger(WordListElement.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private void removeWords(int wordAmount) {
        while (words.size() > wordAmount) {
            words.remove((int) (Math.random() * words.size()));
        }
    }
}
